package com.cubesugar2014.keepup;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * An activity representing a single Item detail screen. This
 * activity is only used on handset devices. On tablet-size devices,
 * item details are presented side-by-side with a list of items
 * in a {@link ItemListActivity}.
 * <p>
 * This activity is mostly just a 'shell' activity containing nothing
 * more than a {@link ItemDetailFragment}.
 */
public class ItemDetailActivity extends FragmentActivity {

	public SContent.SItem mItem;
	private NotificationManager mManager; 
	private Notification.Builder mBuilder;
	//private Bitmap mBitmap;
	private String mKey ;
	private KUInfo mInfo = null;
	private Intent mIntent;
	
	
	public static final String PREFS_NAME = "KeepupPrefsFile";
	 
	public String getPhoneNumber()
    {
	     TelephonyManager mgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	     return mgr.getLine1Number();
	    }
     
    public String getDeviceId()
    {
	     TelephonyManager mgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	     return mgr.getDeviceId();
	}
    
    
    public String getIdKey()
    {
	
    	//return getDeviceId() + ItemDetailFragment.ARG_ITEM_ID + getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID);
    
    	String id = getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID);
    	return getDeviceId() + SContent.ITEM_MAP.get(id);
    	
	}
    
    
    
    
    public static class KUInfo {
    	public String url;
        public String id;
        public String password;
        public String note;

        public KUInfo(String url, String id, String password, String note) {
            this.url = url;
            this.id = id;
            this.password = password;
            this.note = note;
        }
        
        public KUInfo(String total) {
        	
        	String[] arr = total.split("\n");

        	this.url = arr[0].substring(1);
            this.id  = arr[1].substring(1);
            this.password = arr[2].substring(1);
            this.note     = arr[3].substring(1);
        }

        @Override
        public String toString() {
            return "@" + url + "\n" + "@" + id + "\n" + "@" + password + "\n" + "@" + note + "\n";
        }
    }
    
	private KUInfo _LoadInfo(String seedKey) 
	{
		byte[] encryptedData = null;
        
        try {
			
			FileInputStream fIn = openFileInput(seedKey + ".bin");
			long size = fIn.getChannel().size();
			 
			if (size <= 0 )
	            return null;
			 
			encryptedData = new byte[(int) size] ;
			
			
			fIn.read(encryptedData);
			fIn.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    return null;
		}
        
		byte[] key = seedKey.getBytes();    
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		key = sha.digest(key);
		key = Arrays.copyOf(key, 16); // use only first 128 bit
		
		byte[] decryptedData = null;
		
		// decrypt
		try {
			decryptedData = decrypt(key, encryptedData);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return new KUInfo(new String(decryptedData,0,decryptedData.length));
    }
	
	private boolean _SaveInfo(KUInfo info) 
	{
		
		byte[] b = null;
		b = info.toString().getBytes();
		
		//mKey = getDeviceId() + ItemDetailFragment.ARG_ITEM_ID + getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID);
           
		mKey = getIdKey();
				
		byte[] key = mKey.getBytes();    
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		key = sha.digest(key);
		key = Arrays.copyOf(key, 16); // use only first 128 bit
		
		// encrypt
		byte[] encryptedData = null;
		
		try {
			encryptedData = encrypt(key,b);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Toast.makeText(getApplicationContext(), mKey + ".bin" + "encrypted finished", Toast.LENGTH_LONG).show();
        
		try {
			
			FileOutputStream fOut = openFileOutput(mKey + ".bin",Context.MODE_PRIVATE);
			fOut.write(encryptedData);
			fOut.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
    }

	private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }
    
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_detail);

        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // savedInstanceState is non-null when there is fragment state
        // saved from previous configurations of this activity
        // (e.g. when rotating the screen from portrait to landscape).
        // In this case, the fragment will automatically be re-added
        // to its container so we don't need to manually add it.
        // For more information, see the Fragments API guide at:
        //
        // http://developer.android.com/guide/components/fragments.html
        //
        
        
        //make a widget 
        Button save = (Button)findViewById(R.id.button1);
        
        save.setOnClickListener(new OnClickListener(){
        	
        	@Override
        	public void onClick(View v)
        	{
        		//Toast.makeText(getApplicationContext(),"button 1 pressed", Toast.LENGTH_LONG).show();

        		  EditText url = (EditText)findViewById(R.id.EditText_URL); 	    		
        		  EditText id = (EditText)findViewById(R.id.EditText_ID);
        		  EditText password = (EditText)findViewById(R.id.EditText_password);
        		  EditText note = (EditText)findViewById(R.id.EditText_note);
        		      			
        		  
        		  mInfo = new KUInfo(url.getText().toString(), id.getText().toString(), password.getText().toString(), note.getText().toString());
        		  
        		  _SaveInfo(mInfo);
        		
        	}
        });

        Button select = (Button)findViewById(R.id.button2);
        
        
        select.setOnClickListener(new OnClickListener(){
        	
        	@Override
        	public void onClick(View v)
        	{
        		//clean up
        		
        		EditText url = (EditText)findViewById(R.id.EditText_URL); 	    		
       		  	EditText id = (EditText)findViewById(R.id.EditText_ID);
       		  	EditText password = (EditText)findViewById(R.id.EditText_password);
       		  	EditText note = (EditText)findViewById(R.id.EditText_note);
       		  	
       		  	if (mInfo != null)
       		  	{
       		  		url.setText(mInfo.url);
       		  		id.setText(mInfo.id);
       		  		password.setText(mInfo.password);
       		  		note.setText(mInfo.note);
       		  	}
       		  	else 
       		  	{
	       		  	url.setText("");
	   		  		id.setText("");
	   		  		password.setText("");
	   		  		note.setText("");
       		  	}
       		  	
            }
        });
        
        Button activate = (Button)findViewById(R.id.button3);
        	
        mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, SDoSomething.class), PendingIntent.FLAG_UPDATE_CURRENT);
		mIntent = new Intent(this, SDoSomething.class);
	     
		mBuilder = new Notification.Builder(this);
		mBuilder.setSmallIcon(R.drawable.ic_launcher);
		mBuilder.setTicker("Activated your password");
		mBuilder.setWhen(System.currentTimeMillis());

		mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
		mBuilder.setAutoCancel(true);
		 
		//mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
		
        activate.setOnClickListener(new OnClickListener(){
        	
        	@Override
        	public void onClick(View v)
        	{
        		if (mInfo != null)
        		{
        			
        			mBuilder.setContentTitle("Site:" + mInfo.url);
        			mBuilder.setContentText("Id:"+ mInfo.id);
        			
        			//CheckBox cb = (CheckBox)findViewById(R.id.checkBox1);
        			Boolean cb = getIntent().getBooleanExtra("Hidden", false);
            		String password;
        			
        			if (cb)
        				password = " Password:" + "********";
        			else 
        				password = " Password:" + mInfo.password;
        			
        			mIntent.putExtra("Password", mInfo.password);
        			    
        			PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        			mBuilder.setContentIntent(pendingIntent);
        			mBuilder.setContentTitle("Site:" + mInfo.url);
        			mBuilder.setContentText("Id:"+ mInfo.id + password);
        			
	        		//mManager.notify(111, mBuilder.build());
        			mManager.notify(111, mBuilder.getNotification());
	        		
	        	    //Toast.makeText(getApplicationContext(),"This card is activated now", Toast.LENGTH_LONG).show();
	        	 	
	        	    // We need an Editor object to make preference changes.
	        	    // All objects are from android.context.Context
	        	    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	        	    SharedPreferences.Editor editor = settings.edit();
	        	    editor.putString("recentKey", mKey);
	
	        	    // Commit the edits!
	        	    editor.commit();
        		}
        	    /* error
        		ImageView iView = (ImageView)findViewById(R.id.ImageView01);
    			
        		if (iView != null)
        		{
        			try
        			{
        				iView.setVisibility(View.INVISIBLE);
        				iView.setImageBitmap(mBitmap);
        				iView.setVisibility(View.VISIBLE);
                		
        			}catch(Exception e) 
        			{
                        // TODO Auto-generated catch block
                        e.printStackTrace();
        			}
        		}
    			*/
        	      
            }
        });
        
        if (savedInstanceState == null) {
         
        	/*
        	// Create the detail fragment and add it to the activity
            // using a fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
                    getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
            ItemDetailFragment fragment = new ItemDetailFragment();
            fragment.setArguments(arguments);
            
            getSupportFragmentManager().beginTransaction()
                   .add(R.id.item_detail_container, fragment)
                  .commit();
            
            //mItem = fragment.mItem;
            */
            //mKey = getDeviceId() + ItemDetailFragment.ARG_ITEM_ID + getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID);
            

    		mKey = getIdKey();
    		
            mInfo = _LoadInfo(mKey);
           
            EditText url = null;
            
         	if (mInfo != null)
   		  	{
         		
         		url = (EditText)findViewById(R.id.EditText_URL); 	    		
        		EditText id = (EditText)findViewById(R.id.EditText_ID);
        		EditText password = (EditText)findViewById(R.id.EditText_password);
        		EditText note = (EditText)findViewById(R.id.EditText_note);
        		
   		  		url.setText(mInfo.url);
   		  		id.setText(mInfo.id);
   		  		password.setText(mInfo.password);
   		  		note.setText(mInfo.note);
   		  	}
            
         	if (url != null)
         		url.requestFocus();
        }
        
    }

    private File File(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
		if (resultCode == RESULT_OK) 
		{
            
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
